package com.wbt.spring.e02.dao;


import com.wbt.common.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void addUser(User user){
        // 1 创建 sql 语句
        String sql = "insert into user(age,userName,work) values(?,?,?)";
        // 2 调用方法实现
        Object[] args = { user.getAge(), user.getUserName(), user.getWork() };
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    public int selectCount() {
        String sql = "select count(0) from user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public User findUserInfo(String id) {
        String sql = "select id,age,userName,`work` from user where id=?";
        User user = jdbcTemplate.queryForObject(sql, new
                BeanPropertyRowMapper<User>(User. class),id);
        return user;
    }

    public List<User> findAllUser() {
        String sql = "select id,age,userName,`work` from user";
        List<User> list = jdbcTemplate.query(sql, new
                BeanPropertyRowMapper<User>(User. class));
        return list;
    }
}
